import anime from 'animejs'
import { edgeConfig } from '../config/edgeConfig'
import { sizeConfig } from '../config/sizeConfig'
import { BoolType, IDataValue, IModuleWithState } from '../types'
import { uiItems } from '../uiItems'
import {
    createDataValue,
    getCenterPoint,
    setDomBoolVal,
    setDomDataItemVal,
    toBinaryStr,
} from '../utils'
import { bus1 } from './bus'

interface IOutputState {
    out_en: BoolType
    value: number
}

interface IOutput extends IModuleWithState<IOutputState> {
    dataItem: IDataValue<number> | null
    shumaguanAnim: (value: number) => Promise<void>
    timer: any
}

const numToShumaguanMap = {
    0: '00000011',
    1: '10011111',
    2: '00100101',
    3: '00001101',
    4: '10011001',
    5: '01001001',
    6: '01000001',
    7: '00011111',
    8: '00000001',
    9: '00001001',
    d: '11111111',
}

const lightShumaguan = (num: number) => {
    let str = 'd' + num.toString().padStart(3, '0')
    if (num < 0 || num > 999) {
        str = 'dddd'
    }
    const arr = str.split('')
    console.log('light')
    arr.forEach((item, index) => {
        //@ts-ignore
        const binary = numToShumaguanMap[item] as string
        const binaryArr = binary.split('')
        binaryArr.forEach((v, i) => {
            const code = 'a'.charCodeAt(0) + i
            const char = String.fromCharCode(code)
            const shumaguanContainer = uiItems.shumaguan
            const currShumaguan = shumaguanContainer.children![index]
            const dom = currShumaguan.findOne(`.${char}`)
            // const className = `.shumaguan-item-${index + 1} .lamp-${char}`
            // const dom = $(className)
            if (!dom) return
            if (v === '0') {
                dom.fill = '#f00'
                // dom?.classList.add('light')
            } else {
                dom.fill = '#fff'
                // dom?.classList.remove('light')
            }
        })
    })
}

/**
 * output模块
 */
export const output: IOutput = {
    name: 'output',
    dataItem: null,
    timer: null,
    state: {
        out_en: 0,
        value: 0,
    },
    async setState(prop, value) {
        this.state[prop] = value
        if (prop === 'out_en') {
            setDomBoolVal(prop, this.state[prop] as BoolType)
        } else if (prop === 'value') {
            setDomDataItemVal(
                '.output.data-item',
                'output:' + toBinaryStr(this.state[prop])
            )
        }
        if (prop !== 'value') {
            const delay = edgeConfig.time.neg + edgeConfig.time.low
            if (delay === 0) {
                this.change!()
                return
            }
            if (this.timer) {
                clearTimeout(this.timer)
            }
            this.timer = setTimeout(() => {
                this.change!()
            }, delay)
        }
        return
    },
    async change() {
        if (this.state.out_en !== 1) {
            return
        }
        const value = bus1.getData()
        if (value === this.state.value) {
            return
        }
        this.setState('value', value)
        this.shumaguanAnim(value)
    },

    async shumaguanAnim(value: number) {
        console.log(value)
        const leftPoint = getCenterPoint(sizeConfig.savesig, 'left')
        const savesigCenterPoint = getCenterPoint(sizeConfig.savesig)
        const changeToBCDCenterPoint = getCenterPoint(sizeConfig.changeToBCD)
        const segmentCenterPoint = getCenterPoint(sizeConfig.segment)
        const sevenSegmentCenterPoint = getCenterPoint(sizeConfig.sevenSegment)
        const shumaguanCenterPoint = getCenterPoint(
            sizeConfig.shumaguan,
            'bottom'
        )

        if (!this.dataItem) {
            this.dataItem = createDataValue(value, toBinaryStr(value), {
                x: leftPoint.x,
                y: leftPoint.y - 10,
            })
        }
        // this.dataItem!.dom.style.display = 'block'

        this.timeline = anime
            .timeline({
                targets: this.dataItem.dom,
                duration: (edgeConfig.time.neg + edgeConfig.time.low) * 0.05,
                easing: 'linear',
                complete: () => {
                    // console.log('3')
                    lightShumaguan(value)
                    // this.dataItem!.dom.style.display = 'none'
                    this.dataItem!.dom.remove()
                    this.dataItem = null
                },
            })
            .add({
                x: savesigCenterPoint.x,
                y: savesigCenterPoint.y - 10,
            })
            .add({
                x: changeToBCDCenterPoint.x,
                y: changeToBCDCenterPoint.y - 10,
            })
            .add({
                x: segmentCenterPoint.x,
                y: segmentCenterPoint.y - 10,
            })
            .add({
                x: sevenSegmentCenterPoint.x,
                y: sevenSegmentCenterPoint.y - 10,
            })
            .add({
                x: shumaguanCenterPoint.x,
                y: shumaguanCenterPoint.y - 10,
            })
    },
    init() {
        // 设置out_en的初始值
        setDomBoolVal('out_en', this.state.out_en)
        // 设置output
        setDomDataItemVal(
            '.output.data-item',
            'output:' + toBinaryStr(this.state['value'])
        )
    },
}
